import { Popconfirm, message } from 'antd';
import {
    postApiBlackWhiteListBlacklist as addBlacklist,
    deleteApiBlackWhiteListBlacklist as delBlacklist
} from '@/services/furion-cms/blackWhiteList';

import React from 'react';
import { useIntl } from 'umi';
import PermissionsDefinition from '@/permissionsDefinition';
import { useCustomAccess } from '@/components/CustomAccess';

type BlackOptionProps = {
    hasBlacklist?: boolean;
    ipAddress?: string;
    callback?: () => void;
}

/**
 * 黑名单操作选项
 * @param hasBlacklist 是黑名单
 * @param ipAddress Ip地址
 * @returns
 */
export const BlackOptions: React.FC<BlackOptionProps> = ({ hasBlacklist, ipAddress, callback }) => {

    /**
     * @en-US International configuration
     * @zh-CN 国际化配置
     * */
    const intl = useIntl();
    const AccessConfirm = useCustomAccess(Popconfirm);

    const addBlacklistConfirm = async (val?: string | undefined) => {
        const blacklistInput: API.BlacklistInputDto = {
            ipAddress: val,
            description: '登录日志拉黑名单'
        };
        try {
            await addBlacklist([blacklistInput]);
            callback?.()
            message.success(intl.formatMessage({
                id: 'pages.loginRecord.blacklist.add.success',
                defaultMessage: '加入黑名单成功',
            }));
        }
        catch { }
    };

    const removeBlacklistConfirm = async (val?: string | undefined) => {
        try {
            await delBlacklist([(val || "")]);
            callback?.()
            message.success(intl.formatMessage({
                id: 'pages.loginRecord.blacklist.remove.success',
                defaultMessage: '移除黑名单成功',
            }));
        }
        catch { }
    };

    return (<AccessConfirm key="blackWhitelist"
        code={PermissionsDefinition.LoginAuditLogs.BlackWhitelistManager}
        title={intl.formatMessage({
            id: hasBlacklist ? 'pages.loginRecord.blacklist.remove.confirm'
                : 'pages.loginRecord.blacklist.add.confirm',
            defaultMessage: hasBlacklist ? '您确认将「{ipAddress}」从黑名单中移除？'
                : '您确认将「{ipAddress}」加入到黑名单中？',
        }, { ipAddress })}
        onConfirm={() => hasBlacklist ? removeBlacklistConfirm(ipAddress) : addBlacklistConfirm(ipAddress)}
    >
        <a href="#">
            {intl.formatMessage({
                id: hasBlacklist ? 'pages.loginRecord.blacklist.remove'
                    : 'pages.loginRecord.blacklist.add',
                defaultMessage: hasBlacklist ? '移除黑名单' : '加入黑名单',
            })}
        </a>
    </AccessConfirm>);
}

